"""
文件名：views.py
作者：教务系统开发团队
创建日期：2025-04-27
描述：用户认证模块的视图，处理用户认证相关的API请求
"""
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Parent, ParentStudentRelationship
from .serializers import ParentSerializer, ParentStudentRelationshipSerializer
from students.models import Student

class ParentViewSet(viewsets.ModelViewSet):
    """
    家长用户视图集
    
    功能：
        - 家长用户的CRUD操作
        - 家长关联学生管理
    """
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    @action(detail=True, methods=['get', 'post', 'delete'], url_path='students')
    def manage_students(self, request, pk=None):
        """
        管理家长关联的学生
        
        GET: 获取家长关联的所有学生
        POST: 为家长添加学生关联
        DELETE: 移除家长与学生的关联
        """
        parent = self.get_object()
        
        if request.method == 'GET':
            # 获取关联学生列表
            relationships = parent.parentstudentrelationship_set.all()
            serializer = ParentStudentRelationshipSerializer(relationships, many=True)
            return Response(serializer.data)
            
        elif request.method == 'POST':
            # 添加学生关联
            serializer = ParentStudentRelationshipSerializer(data=request.data)
            if serializer.is_valid():
                student = serializer.validated_data['student_id']
                is_primary = serializer.validated_data.get('is_primary', False)
                
                # 检查是否已关联
                if parent.parentstudentrelationship_set.filter(student=student).exists():
                    return Response(
                        {'detail': '该学生已关联'},
                        status=status.HTTP_400_BAD_REQUEST
                    )
                
                # 检查学生联系人手机号是否匹配
                if student.contact_phone != parent.phone:
                    return Response(
                        {'detail': '手机号码与学生联系人手机号不匹配'},
                        status=status.HTTP_400_BAD_REQUEST
                    )
                
                # 创建关联
                ParentStudentRelationship.objects.create(
                    parent=parent,
                    student=student,
                    is_primary=is_primary
                )
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            
        elif request.method == 'DELETE':
            # 移除学生关联
            student_id = request.data.get('student_id')
            if not student_id:
                return Response(
                    {'detail': '缺少student_id参数'},
                    status=status.HTTP_400_BAD_REQUEST
                )
                
            try:
                student = Student.objects.get(student_id=student_id)
                relationship = parent.parentstudentrelationship_set.get(student=student)
                relationship.delete()
                return Response(status=status.HTTP_204_NO_CONTENT)
            except Student.DoesNotExist:
                return Response(
                    {'detail': '学生不存在'},
                    status=status.HTTP_404_NOT_FOUND
                )
            except ParentStudentRelationship.DoesNotExist:
                return Response(
                    {'detail': '未找到该关联关系'},
                    status=status.HTTP_404_NOT_FOUND
                )